package com.beyondsoft.common.core.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 分布式事务redis工具类
 */
@Service
public class RedisMsService {

    @Autowired
    protected RedisTemplate redisTemplate;
    //配置超时时间
    @Value("${redis.ms-timeout-second}")
    private Long redisTimeOut;

    /**
     * 写入request的请求事务组缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, redisTimeOut, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 根据key前缀查找
     *
     * @param key
     * @return
     */
    public Set<String> getKeyList(String key) {
        return redisTemplate.keys(key);
    }

}